from netmiko import ConnectHandler

# 定义连接信息
squid = {
    'device_type': 'linux',
    'host': '172.26.132.177',
    'username': 'root',
    'password': '5star.com'
}


# 添加ip白名单
def add_ip(hosts, description):
    global squid
    net_connect = ConnectHandler(**squid)
    # 自定义shell语句
    hosts = str(hosts)
    description = str(description)
    str_command = 'echo acl local src ' + hosts + '\ \ \ \ ' + '#' + description + ' >> /etc/squid/srcip.acl'
    # 强行转换命令格式为str
    str_command = str(str_command)
    # 执行
    net_connect.send_command(str_command)
    # 关闭连接
    net_connect.disconnect()


# 删除IP白名单
def del_ip(hosts):
    global squid
    net_connect = ConnectHandler(**squid)
    # 自定义shell语句
    hosts = str(hosts)
    str_command = "sed -i '/" + hosts + "/d' /etc/squid/ipacl.conf"
    # 强行转换命令格式为str
    str_command = str(str_command)
    # 执行
    net_connect.send_command(str_command)
    # 关闭连接
    net_connect.disconnect()


# 添加目的域名白名单
def add_white_list(dstdomain):
    global squid
    net_connect = ConnectHandler(**squid)
    # 自定义shell语句
    dstdomain = str(dstdomain)
    str_command = 'echo acl White_List dstdomain ' + dstdomain + ' >> /etc/squid/desdomain.acl'
    # 强行转换命令格式为str
    str_command = str(str_command)
    # 执行
    net_connect.send_command(str_command)
    # 关闭连接
    net_connect.disconnect()


# 删除目的域名白名单
def del_white_list(dstdomain):
    global squid
    net_connect = ConnectHandler(**squid)
    # 自定义shell语句
    dstdomain = str(dstdomain)
    str_command = "sed -i '/" + dstdomain + "/d' /etc/squid/desdomain.acl"
    # 强行转换命令格式为str
    str_command = str(str_command)
    # 执行
    net_connect.send_command(str_command)
    # 关闭连接
    net_connect.disconnect()


# 重启squid服务
def restart_squid():
    global squid
    net_connect = ConnectHandler(**squid)
    # 自定义shell语句
    str_command = 'systemctl restart squid'
    str_command = str(str_command)
    net_connect.send_command(str_command)
    # 关闭连接
    net_connect.disconnect()


def touch_file():
    global squid
    net_connect = ConnectHandler(**squid)
    # 自定义shell语句
    # str_command = 'touch /root/mcwnibi.666'
    str_command = 'ls'
    str_command = str(str_command)
    net_connect.send_command(str_command)
    # 关闭连接
    net_connect.disconnect()


# a = "192.168.1.1"
# b = "这是一个测试"
# add_ip(a, b)

# 查看配置文件
def cat_file():
    global squid
    net_connect = ConnectHandler(**squid)
    # 自定义shell语句
    str_command = "sed 's/.* //' /etc/squid/desdomain.acl"
    str_command = str(str_command)
    output = net_connect.send_command(str_command)
    print(output)
    # 关闭连接
    net_connect.disconnect()


cat_file()
